#include <iostream>
#include <sstream>
#include "SingleCallDataVectorParser.h"

#include "ParameterParser.h"
#include "Scenario.h"


SingleCallDataVectorParser::SingleCallDataVectorParser(
                                string scenarioFileName,int threadNumber)
{
    Scenario scenario(scenarioFileName);
        
    _data.clear();       //for when we wonna load a new file
    
    _data.push_back(""); //first string HAS TO BE:  'from <sip:user@server>'
                         //just making sure there is place for it

    scenario.setFirstLine(); // start reading in a file, line by line
    
    while (scenario.hasNextLine())
    {
        string sep = ",";
        string command =  scenario.getNextLine();
        // strip of leading whitespaces and tabs
        while (command.find_first_of(sep) == 0)
        {
            command = command.substr(1,command.size());
        }
        // if empty line or comment, go to next line
        if (command.size() != 0 && command.at(0) != '#' )
        {
            // strip of trailing whitespaces and tabs
            while (command.find_last_of(sep) == command.size()-1)
            {   
                command = command.substr(0,command.size()-1);
            }
            command = findReplaceVariable(command,threadNumber);
            _data.push_back(command);
        }
        
    }
    std::ostringstream fromIdentity;
    int username = atoi(ParameterParser::getInstance()->parseParameter("user", threadNumber).c_str());
    string server = ParameterParser::getInstance()->parseParameter("server", threadNumber);
    fromIdentity << "from <sip:" << username << "@" << server << ">";
    _data[0]=fromIdentity.str();
}

SingleCallDataVectorParser::~SingleCallDataVectorParser()
{
    //empty destructor
}

vector<string> SingleCallDataVectorParser::getDataVector()
{
    return _data;
}


string SingleCallDataVectorParser::findReplaceVariable(string token, 
                                                       int threadNumber)
{
   uint locBegin=0;
   while( (locBegin = token.find("${")) != string::npos )
   {
        string param="";
        uint locEnd =0;

        if ( (locEnd = token.find("}",locBegin)) != string::npos )
        {
            string temp;
            param = token.substr( (locBegin+2), (locEnd-locBegin-2) );
            temp = ParameterParser::getInstance()->parseParameter(param, threadNumber);
            if(temp =="")
            {
                std::cerr << "Parameter '"<< param <<"' not found ";
                std::cerr << "(not in this thread and not in global)." << std::endl;
                std::cerr << "It was searched in file: '";
                std::cerr << ParameterParser::getInstance()->getScenarioFilename();
                std::cerr << "'" << std::endl;
                //exit(1);  // too severe
            }
            token.replace( (locBegin), (locEnd-locBegin+1),temp);
        }
   }
   return token;
}
